var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');
const pageInterceptor = require('../../../components/pageInterceptor').pageInterceptor;
const api = require('../../../api/api');
const request = require('../../../components/request');
const util = require('../../../utils/util');

/**
 * qq地图对象
 */
var qqmapsdk;

// Page({
pageInterceptor({
  isDefault: false,
  /**
   * 保存地址
   * @param {*} e 
   */
  formSubmit: function (e) {
    // userInfo 
    var userInfo = wx.getStorageSync('userInfo');
    // detail
    var detail = e.detail.value.detail;
    // realName
    var realName = e.detail.value.realName;
    // mobile
    var mobile = e.detail.value.mobile;

    // 表单验证
    if (this.data.areaSelectedStr == '请选择省市区') {
      wx.showToast({
        title: '请输入区域'
      });
      return;
    }
    if (detail == '') {
      wx.showToast({
        title: '请填写详情地址'
      });
      return;
    }
    if (realName == '') {
      wx.showToast({
        title: '请填写收件人'
      });
      return;
    }
    if (!(/^1[34578]\d{9}$/.test(mobile))) {
      wx.showToast({
        title: '请填写正确手机号码'
      });
      return;
    }

    // save address
    var address;
    // 如果是编辑地址而不是新增
    if (this.data.address != undefined) {
      address = this.data.address;
    }
    // if isDefault address
    address.isDefault = this.isDefault;
    address.detail = detail;
    // set province city region
    address.province = this.data.province[this.data.provinceIndex];
    address.city = this.data.city[this.data.cityIndex];
    address.region = this.data.region[this.data.regionIndex];
    address.town = this.data.town[this.data.townIndex];
    address.userId = userInfo.userId;
    address.realName = realName;
    address.mobile = mobile;
    var url = api.data.prefix + api.data.url.relUserAddress.add;
    request.post(url, address, {
      'content-type': 'application/json',
    }).action((res) => {
      console.log(`接口${api.data.url.relUserAddress.add}：${JSON.stringify(res)}`);
      wx.showToast({
        title: '保存成功',
        duration: 500
      });
      // 等待半秒，toast消失后返回上一页
      setTimeout(function () {
        wx.navigateBack();
      }, 500);
    }).catch(err => {
      console.error(err);
    });
  },
  data: {
    /**
     * 地址
     */
    address: {},
    /**
     * 该选择省时，为0；该选择市时，为1；该选择县时，为2
     */
    current: 0,
    /**
     * 省的数组
     */
    province: [],
    /**
     * 市的数组
     */
    city: [],
    /**
     * 县的数组
     */
    region: [],
    town: [],
    /**
     * 省的对象数组
     */
    provinceObjects: [],
    /**
     * 市的对象数组
     */
    cityObjects: [],
    /**
     * 县的对象数组
     */
    regionObjects: [],
    townObjects: [],
    areaSelectedStr: '请选择省市区',
    maskVisual: 'hidden',
    provinceName: '请选择'
  },
  /**
   * 根据parentId，获取area数组
   * @param {*} pid 
   * @param {*} cb 
   */
  getArea: function (pid, cb) {
    var url = util.restfulFormat(api.data.prefix + api.data.url.area.findByParentId, { parentId: pid });
    request.get(url, null, {
      'content-type': 'application/json',
    }).action((res) => {
      console.log(`接口${api.data.url.area.findByParentId}：${JSON.stringify(res)}`);
      cb(res.data.result);
    }).catch(err => {
      console.error(err);
    });
  },
  onLoad: function (options) {
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'BJFBZ-ZFTHW-Y2HRO-RL2UZ-M6EC3-GMF4U'
    });

    // 查询省的记录
    let that = this;
    request.get(api.data.prefix + api.data.url.area.findAllProvince, null, {
      'content-type': 'application/json',
    }).action((res) => {
      console.log(`接口${api.data.url.area.findAllProvince}：${JSON.stringify(res)}`);
      var array = [];
      var areaArray = res.data.result;
      for (var i = 0; i < areaArray.length; i++) {
        array[i] = areaArray[i].name;
      }
      that.setData({
        province: array,
        provinceObjects: areaArray
      });
    }).catch(err => {
      console.error(err);
    });

    // 如果当前用户没有地址，则isDefault设置为true
    this.setDefault();
    this.loadAddress(options);
  },
  // 因为options.objectId为空，所以这个方法实际上算是没有执行
  loadAddress: function (options) {
    var that = this;
    if (options.objectId != undefined) {
      // 第一个参数是 className，第二个参数是 objectId
      var address = AV.Object.createWithoutData('Address', options.objectId);
      address.fetch().then(function () {
        that.setData({
          address: address,
          areaSelectedStr: address.get('province') + address.get('city') + address.get('region') + address.get('town')
        });
      }, function (error) {
        // 异常处理
      });
    }
  },
  /**
   * 如果当前用户没有地址，则isDefault设置为true
   */
  setDefault: function () {
    let userId = wx.getStorageSync('userInfo').userId;
    let that = this;
    var url = util.restfulFormat(api.data.prefix + api.data.url.relUserAddress.countByUserId, { userId: userId });
    request.get(url, null, {
      'content-type': 'application/json',
    }).action((res) => {
      console.log(`接口${api.data.url.relUserAddress.countByUserId}：${JSON.stringify(res)}`);
      if (res.data.result <= 0) {
        that.isDefault = true;
      }
    }).catch(err => {
      console.error(err);
    });
  },
  /**
   * 点击请选择省市区
   */
  cascadePopup: function () {
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-in-out',
    });
    this.animation = animation;
    animation.translateY(-285).step();
    this.setData({
      animationData: this.animation.export(),
      maskVisual: 'show'
    });
  },
  /**
   * 点击弹出框的关闭按钮
   */
  cascadeDismiss: function () {
    this.animation.translateY(285).step();
    this.setData({
      animationData: this.animation.export(),
      maskVisual: 'hidden'
    });
  },
  /**
   * 所在地区下拉列表中，省一级的选项被选择时
   * @param {*} e 
   */
  provinceTapped: function (e) {
    debugger;
    // 标识当前点击省份，记录其名称与主键id都依赖它
    var index = e.currentTarget.dataset.index;
    // current为1，使得页面向左滑动一页至市级列表
    // provinceIndex是市区数据的标识
    this.setData({
      provinceName: this.data.province[index],
      regionName: '',
      townName: '',
      provinceIndex: index,
      cityIndex: -1,
      regionIndex: -1,
      townIndex: -1,
      region: [],
      town: []
    });
    var that = this;
    //provinceObjects是一个LeanCloud对象，通过遍历得到纯字符串数组
    // getArea方法是访问网络请求数据，网络访问正常则一个回调function(area){}
    this.getArea(this.data.provinceObjects[index].id, function (area) {
      var array = [];
      for (var i = 0; i < area.length; i++) {
        array[i] = area[i].name;
      }
      // city就是wxml中渲染要用到的城市数据，cityObjects是LeanCloud对象，用于县级标识取值
      that.setData({
        cityName: '请选择',
        city: array,
        cityObjects: area
      });
      // 确保生成了数组数据再移动swiper
      that.setData({
        current: 1
      });
    });
  },
  /**
   * 所在地区下拉列表中，市一级的选项被选择时
   * @param {*} e 
   */
  cityTapped: function (e) {
    debugger;
    // 标识当前点击县级，记录其名称与主键id都依赖它
    var index = e.currentTarget.dataset.index;
    // current为1，使得页面向左滑动一页至市级列表
    // cityIndex是市区数据的标识
    this.setData({
      cityIndex: index,
      regionIndex: -1,
      townIndex: -1,
      cityName: this.data.city[index],
      regionName: '',
      townName: '',
      town: []
    });
    var that = this;
    //cityObjects是一个LeanCloud对象，通过遍历得到纯字符串数组
    // getArea方法是访问网络请求数据，网络访问正常则一个回调function(area){}
    this.getArea(this.data.cityObjects[index].id, function (area) {
      var array = [];
      for (var i = 0; i < area.length; i++) {
        array[i] = area[i].name;
      }
      // region就是wxml中渲染要用到的城市数据，regionObjects是LeanCloud对象，用于县级标识取值
      that.setData({
        regionName: '请选择',
        region: array,
        regionObjects: area
      });
      // 确保生成了数组数据再移动swiper
      that.setData({
        current: 2
      });
    });
  },
  regionTapped: function (e) {
    debugger;
    // 标识当前点击镇级，记录其名称与主键id都依赖它
    var index = e.currentTarget.dataset.index;
    // current为1，使得页面向左滑动一页至市级列表
    // regionIndex是县级数据的标识
    this.setData({
      regionIndex: index,
      townIndex: -1,
      regionName: this.data.region[index],
      townName: ''
    });
    var that = this;
    //townObjects是一个LeanCloud对象，通过遍历得到纯字符串数组
    // getArea方法是访问网络请求数据，网络访问正常则一个回调function(area){}
    this.getArea(this.data.regionObjects[index].id, function (area) {
      // 假如没有镇一级了，关闭悬浮框，并显示地址
      if (area.length == 0) {
        var areaSelectedStr = that.data.provinceName + that.data.cityName + that.data.regionName;
        that.setData({
          areaSelectedStr: areaSelectedStr
        });
        that.cascadeDismiss();
        return;
      }
      var array = [];
      for (var i = 0; i < area.length; i++) {
        array[i] = area[i].name;
      }
      // region就是wxml中渲染要用到的县级数据，regionObjects是LeanCloud对象，用于县级标识取值
      that.setData({
        townName: '请选择',
        town: array,
        townObjects: area
      });
      // 确保生成了数组数据再移动swiper
      that.setData({
        current: 3
      });
    });
  },
  // 由于没有区的数据，因此这个方法没有被使用
  townTapped: function (e) {
    debugger;
    // 标识当前点击镇级，记录其名称与主键id都依赖它
    var index = e.currentTarget.dataset.index;
    // townIndex是镇级数据的标识
    this.setData({
      townIndex: index,
      townName: this.data.town[index]
    });
    var areaSelectedStr = this.data.provinceName + this.data.cityName + this.data.regionName + this.data.townName;
    this.setData({
      areaSelectedStr: areaSelectedStr
    });
    this.cascadeDismiss();
  },
  /**
   * 所在地区下拉列表中，选择了一项后，触发这个事件
   * @param {*} e 
   */
  currentChanged: function (e) {
    // swiper滚动使得current值被动变化，用于高亮标记
    var current = e.detail.current;
    this.setData({
      current: current
    });
  },
  /**
   * 所在地区下拉列表中，之前被选中的项，再次被点击之后触发这个事件
   */
  changeCurrent: function (e) {
    // 记录点击的标题所在的区级级别
    var current = e.currentTarget.dataset.current;
    this.setData({
      current: current
    });
  },
  /**
   * 获取地理位置
   */
  fetchPOI: function () {
    var that = this;
    wx.getLocation({
      type: 'gcj02', //wgs84 返回 gps 坐标，gcj02 
      altitude: true, //传入 true 会返回高度信息，由于获取高度需要较高精确度，会减慢接
      isHighAccuracy: false, //开启高精度定位
      highAccuracyExpireTime: 3000, //高精度定位超时时间(ms)，3000ms以上定位才有效果
      success(res) {
        let location = {};
        location.horizontalAccuracy = res.horizontalAccuracy;
        location.latitude = parseFloat(res.latitude);
        location.longitude = parseFloat(res.longitude);
        console.log(`纬度是${location.latitude}，经度是${location.longitude}`);

        // 调用接口，获取地理位置
        qqmapsdk.reverseGeocoder({
          // poi_options: 'policy=2',
          // get_poi: 1,
          location: {
            latitude: location.latitude,
            longitude: location.longitude
          },
          success: function (res) {
            console.log(`地理位置是${res.result.address}`);
            that.setData({
              areaSelectedStr: res.result.address
            });
          },
          fail: function (res) {
          },
          complete: function (res) {
          }
        });
      },
      fail: function (res) {
        console.error(res)
      }
    });
  }
  // })
}, true)